import React from 'react';
import { Button,Icon,Upload } from 'antd';
import { WeaDialog, WeaRichText, WeaLocaleProvider ,WeaTools} from 'ecCom';
import { ReplyAddStore } from '../../stores/reply/add';
import { observer } from 'mobx-react';
import classnames from 'classnames';
import CubeAt from "../cube-at";
import * as Utils from "../../util";
const getLabel = WeaLocaleProvider.getLabel;
import {writeLog} from "../../util/modeUtil";
import window from '../../util';
import loadjs from "loadjs";
import $ from 'jquery';


export interface ReplyAddProps {
    replyAdd: ReplyAddStore;
    isShowSignInput?: boolean;
    editorId?: string;
    visible?: boolean;
    params:any;
    iconInfo:any;
    windowTop?:any;
}


export default class ReplyAdd extends React.Component<ReplyAddProps, any> {
    rtInstance:any;
    constructor(props) {
        super(props);
        const { remark, visible,windowTop,replyAdd } = props;
        this.state = {
            remark: remark,
            visibleComponent: '',
            visible: visible,
            richContent:replyAdd.content,
            rtInstanceReady:false
        }
        if (!windowTop.CK_REF) {
            windowTop.CK_REF = {};
        }
    }

    componentWillReceiveProps(nextProps: Readonly<ReplyAddProps>, nextContext: any): void {
        this.setState({richContent:nextProps.replyAdd.content})
    }

    /**
     *  回复评富文本框底部按钮
     */
    getbottomBar = () => {
        const { replyAdd } = this.props;
        const{showbuttons}=replyAdd;
        let bottomBarConfig: any[] = [];
            showbuttons.forEach(buttoninfo => {
                if(buttoninfo.isdefault && buttoninfo.fieldhtmltype == "3"){
                    if(buttoninfo.type == "37"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: (
                                <div className="wea-cb-item">
                                    <span className={"wea-cbi-icon-Document"} />
                                    <span className="wea-cbi-text"> <i className='icon-coms-Journal'/> {getLabel(58, "文档")}</span>
                                </div>
                            ),
                            type: "37",
                            isSingle: false,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            title: getLabel(58, "文档")
                        });
                    }else if(buttoninfo.type == "152"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: <div className="wea-cb-item">
                                <span className={"wea-cbi-icon-Process"} />
                                <span className="wea-cbi-text"><i className='icon-coms-Workflow-o'  /> {getLabel(18015, "流程")}</span>
                            </div>,
                            type: "152",
                            isSingle: false,
                            customParams:{'linkUrl':buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            title: getLabel(18015, "流程")
                        })
                    }else if(buttoninfo.type == "18"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: <div className="wea-cb-item">
                                <span className={"wea-cbi-icon-Personnel"} />
                                <span className="wea-cbi-text"><i className='icon-coms-currency-Customer'/> {getLabel(136, "客户")}</span>
                            </div>,
                            type: "18",
                            isSingle: false,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            title: getLabel(136, "客户")
                        })
                    }else if(buttoninfo.type == "135"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: <div className="wea-cb-item">
                                <span className={"wea-cbi-icon-Project"} />
                                <span className="wea-cbi-text"><i className='icon-coms-task-list'/> {getLabel(101, "项目")}</span>
                            </div>,
                            type: "135",
                            isSingle: false,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            title: getLabel(101, "项目")
                        })
                    }
                }else if(buttoninfo.isdefault && buttoninfo.fieldhtmltype == "6"){
                    bottomBarConfig.push(this.getUploadCom('buttom_default',buttoninfo))
                }
                if(!buttoninfo.isdefault){
                    if(buttoninfo.fieldhtmltype == "3"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: <div className="wea-cb-item">
                                <span className="wea-cbi-text"><i className='icon-coms-task-list'/> {buttoninfo.fieldlabelname}</span>
                            </div>,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                           ...buttoninfo.buttonProps
                        })
                    }else if(buttoninfo.fieldhtmltype == "6"){
                        bottomBarConfig.push(this.getUploadCom('buttom_spicial',buttoninfo))
                    }
                }

            });

        return bottomBarConfig;
    }


    getUploadCom = (tooltype,buttoninfo?) => {
        const { replyAdd,params } = this.props;
        const{billid,formId,modeId}=params;
        let uploadObj:any = {};
        let limitType = "";

        let uploadType = [
            {
                type:'top',
                show:<div className="wea-cb-item"><span className={`wea-cbi-icon cke_button_icon cke_button__image_icon`} /></div>,
                uploadUrl:'/api/formmode/card/uploadimage',
                _html:'image',
                category:'all',
            },
            {
                type:'bottom',
                show:<div className="wea-cb-item"><span className={"wea-cbi-icon-File"} /><span className="wea-cbi-text"><Icon type='paper-clip' /> {getLabel(156, '附件')}</span></div>,
                uploadUrl: "/api/formmode/card/replyUpload?category=1&from=reply&mainId=" + replyAdd.maincategory + "&subId=" + replyAdd.subcategory + "&secId=" + replyAdd.seccategory
                    + "&modeid=" + modeId+ "&formid=" + formId+ "&billid=" + billid,
                _html:'file',
                category: replyAdd.maincategory + "," + replyAdd.subcategory + "," + replyAdd.seccategory,
            },
        ]
        if(buttoninfo){
            if(buttoninfo['fieldhtmltype']=='6'&&buttoninfo['type']=='2'){
                limitType = "jpg,gif,png,bmp";
            }
            let secId =replyAdd.seccategory
            if(buttoninfo.seccategory){
                secId = buttoninfo.seccategory;
            }
            uploadType.push(
                {
                    type:'buttom_default',
                    show:<div className="wea-cb-item">
                            <span className={"wea-cbi-icon-File"} />
                            <span className="wea-cbi-text"><Icon type='paper-clip' /> {getLabel(156, '附件')}</span>
                        </div>,
                    uploadUrl: "/api/formmode/card/replyUpload?category=1&from=reply&mainId=" + replyAdd.maincategory + "&subId=" + replyAdd.subcategory + "&secId=" + secId
                        + "&modeid=" + modeId+ "&formid=" + formId+ "&billid=" + billid,
                    _html:'file',
                    category: replyAdd.maincategory + "," + replyAdd.subcategory + "," + replyAdd.seccategory,
                },
                {
                    type:'buttom_spicial',
                    show:<div className="wea-cb-item">
                            <span className={"wea-cbi-icon-File"} />
                            <span className="wea-cbi-text"><Icon type='paper-clip' /> {buttoninfo.fieldlabelname}</span>
                        </div>,
                    uploadUrl: "/api/formmode/card/replyUpload?category=1&from=reply&mainId=" + replyAdd.maincategory + "&subId=" + replyAdd.subcategory + "&secId=" + secId
                        + "&modeid=" + modeId+ "&formid=" + formId+ "&billid=" + billid,
                    _html:'file',
                    category: replyAdd.maincategory + "," + replyAdd.subcategory + "," + buttoninfo.seccategory,
                },
            )
        }
        const upload = uploadType.filter(item => item.type == tooltype)[0];
        if(window !== window.top){
            uploadObj = {
                name: 'Component',
                show: <div>
                    <Upload
                        name = 'file'
                        action= {upload.uploadUrl}
                        accept={upload.type == 'top'? '.jpg,.gif,.png' :''}
                        showUploadList= {false}
                        onChange = {(info)=>{
                            if(info['file'].response){
                                const id = info['file'].response.data.fileid;
                                let listArr:any = []
                                info.fileList.map((item)=>{
                                    if(id == item.response.data.fileid){
                                        item = {...item,...item.response.data}
                                        listArr.push({
                                            ...item,...item.response.data
                                        })
                                    }
                                })
                                const fileHtml = this.toolsChange('Upload',id,listArr,upload._html,'')
                                this.addAtInfo(fileHtml,'upload');
                            }
                        }}
                    >
                        {upload.show}
                    </Upload>
                </div>
            }
        }else{
            uploadObj = {
                name:'Upload',
                show: upload.show,
                uploadUrl: upload.uploadUrl,
                category: upload.category,
            }
            if(upload.type == 'top'){
                uploadObj = {
                    ...uploadObj,
                    type:'image',
                    limitType:'jpg,gif,png',
                    title:'上传图片',
                    needLoading:false
                }
            }else{
                uploadObj = {
                    ...uploadObj,
                    isBlog: true,
                    uploadId: "replyUpload",
                    limitType: limitType,
                    autoUpload: true,
                    multiSelection: false,
                    btnSize: "small",
                }
            }
        }
        if(buttoninfo){
            uploadObj={
                ...uploadObj,
                customParams:{isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid}
            }
        }
        return uploadObj;
    }
    toolsChange = (name, _, list, type,customParams) => {
        (this.rtInstance as any).focus('last'); // 光标置后
        let str = '';
        let linkUrl = customParams?customParams.linkUrl:'';
        let isdefault = customParams?customParams.isdefault:false;
        let fieldid = customParams?customParams.fieldid:'0';
        const mirror = {
             37: "doc",
             task: "task",
             18: "crm",
             152: "workflow",
             135: "project",
            workplan: "workplan",
            blogTemplate: "blogTemplate"
        }
        list.map(item => {
            if (name === 'Upload' && type === 'image') {
                str += '<img class="formImgPlay" src="' + item.filelink + '" data-imgsrc="' + (item.loadlink || item.filelink) + '" />'
            }
            if (name === 'Upload' && type === 'file') {
                    str += (item.filelink + '<br>')
            }
            if (name === 'Browser') {
                // if (mirror[type] == "doc") {//文档
                //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/document/index.jsp?id=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // }
                // // else if(mirror[type] == "task"){
                // //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/document/index.jsp?id=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // // }
                // else if (mirror[type] == "crm") {//客户
                //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/crm/static/index.html#/main/crm/customerView?customerId=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // } else if (mirror[type] == "workflow") {//流程
                //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/workflow/request/ViewRequestForwardSPA.jsp?isrequest=1&requestid=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // } else if (mirror[type] == "project") {//项目
                //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/prj/index.html#/main/prj/projectCard?prjid=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // } else {
                //     str += (type === 'blogTemplate' ? item.name : `<a href='javascript:void(0)'  linkid='${item.id}' linkType='${mirror[type]}' onclick='try{return openAppLink(this,${item.id});}catch(e){}' ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>`)
                // }
                if(isdefault){
                    str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('${linkUrl+item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                }else{
                    str += (type === 'blogTemplate' ? item.name : `<abbr class='custom' id='${fieldid+'_'+item.id}' name='${item.name}'><a href="javascript:modeopenFullWindowHaveBar('${linkUrl+item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a></abbr>`)
                }
               if(mirror[type] == "task"){
                    str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/document/index.jsp?id=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                }
            }
        })
        return str;
    }

    getAtInfo(){
		const {replyAdd,params = {}} = this.props;
		return replyAdd.getAtInfo(params);
	}

	setAtInfo=(k,v)=>{
		const {replyAdd,params = {}} = this.props;
		replyAdd.setAtInfo(k,v,params);
	}

    componentWillMount(){
		const {replyAdd,params = {},windowTop} = this.props;
		const atInfo = this.getAtInfo();
		const {time=''} = atInfo;
		let key = "cube_at_"+params.modeId+"_"+params.billid;
		let now:any = new Date().getTime();
		let isNeedLoad = true;
		if(windowTop.__atdata&&time&&!isNaN(time)){
			if(now-time<1000*60*3){//小于3分钟，不需要再次加载
				isNeedLoad = false;
			}
		}
		let tempatitems:any = [];
		let setAtInfo = this.setAtInfo.bind(this);
		if(isNeedLoad){
			windowTop.jQuery.ajax({
				url: '/api/cube/new/card/getAtUsers',
				type: 'GET', //GET
				data: {modeid:params.modeId,billid:params.billid},
				success: function (result) {
					setAtInfo("time",now);
					const response = JSON.parse(result);
					tempatitems = [];
					response.operators.map(o => {
						tempatitems.push(o);
					});
					replyAdd.atInfo[key+"_data"]={ atitems: tempatitems, _atitems: tempatitems.slice(0, 100) };
					windowTop.__atdataready = true;
					windowTop.__atdata = tempatitems;
				}
			});
		}else{
			tempatitems = windowTop.__atdata;
			windowTop.__atdataready = true;
			replyAdd.atInfo[key+"_data"]={ atitems: tempatitems, _atitems: tempatitems.slice(0, 100) };
		}
	}

    getExtendsBar = () => {
        const { editorId,params,replyAdd,windowTop } = this.props;
        const { visibleComponent } = this.state;
        const extentsConfig = [
            this.getUploadCom('top'),
            {
                name: 'Component',
                show: <CubeAt
                    editorId={editorId}
                    appendHtmlToCKEditor={this.addAtInfo.bind(this)}
                    visible={visibleComponent === 'CubeAt'}
                    showComponent={this.showComponent.bind(this)}
                    params={params}
                    replyAdd={replyAdd}
                    windowTop={windowTop}
                    />
            },
        ]
        return extentsConfig;
    }
    componentDidUpdate() {
        const { visible = false ,replyAdd,windowTop} = this.props;
        if (visible || replyAdd.popup) {
            const ckeditorid = this.rtInstance.editor.container.getId() || "";
            this.initAutoAt(windowTop.$(`#${ckeditorid}`).find('iframe')[0]);
        }
    }

    componentDidMount() {
        const { editorId = "" ,windowTop,} = this.props;
        windowTop.CK_REF[editorId] = this.rtInstance;
        if(windowTop.CK_REF[editorId]){
            let editor = windowTop.CK_REF[editorId].getEditor();
            if(editor){
                editor.focusManager.focus( editor.editable() );

            }
        }
    }

    showComponent(componet) {
        this.setState({ visibleComponent: componet });
    }

    addAtInfo(html,type?) {
        const { editorId = "" ,windowTop} = this.props;
        let _html = html;
        if(windowTop.CK_REF[editorId]){
            const instances = windowTop.CK_REF[editorId].getEditor().ui.instances;
            if (instances && type!== 'upload') {
                const font = instances.Font['_'].value || '微软雅黑';
                const fontsize = instances.FontSize['_'].value || '12';
                _html = `<span style="font-family:'${font}';font-size:${fontsize}px;" >${html}</span>`;
            }
        }



        this.appendHtmlToCKEditor(_html);
    }
    appendHtmlToCKEditor(html, pos?) {
        const {windowTop} = this.props;
        if (pos) {
            this.rtInstance['insertHTML'](Utils.convertSpecialChar(html), pos);
            const el = this.rtInstance;
            const me = this;
            windowTop.$(el).off("click").on("click", function (_) {
                me.setState({ visibleComponent: '' });
            });
        } else {
            this.rtInstance['insertHTML'](Utils.convertSpecialChar(html));
        }
    }

    initAutoAt(ifr) {
        const { editorId ,windowTop} = this.props;
        const me = this;
        const ckeditor = this.rtInstance;
        try {
            let datas = windowTop.__atdata;
            if (windowTop.__atdataready != true || !!!datas) {
                setTimeout(function () {
                    me.initAutoAt(ifr);
                }, 1000);
                return;
            }
            let allatids = ",";
            let names = windowTop.jQuery.map(datas, function (value, _) {
                if (allatids.indexOf("," + value.uid + ",") == -1) {
                    allatids += value.uid + ",";
                    return { 'id': value.uid, 'name': value.data, 'py': value.datapy||"" };
                }
            });
            let at_config = {
                at: "@",
                data: names,
                tpl: "<li data-value='@${name}'>${name}</li>",
                insert_tpl: "<a href='/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/${id}' atsome='@${id}' contenteditable='false' style='cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important;' target='_blank'>${atwho-data-value}</a>",
                limit: 100,
                show_the_at: true,
                start_with_space: false,
                with_repeat_matcher: false,
                search_key_py: 'py',
                ckeditor: ckeditor,
                editorId: editorId,
                save:this.saveAt,
                pageIndex:1,
                pageSize:20,
            }
            let ifrBody = ifr.contentDocument.body;
            windowTop.jQuery(ifrBody)['atwho']('setIframe', ifr).atwho(at_config).on("inserted.atwho", function(a,b,c) {});
            let atwhoblockobj = windowTop.jQuery(".atwho-view");
            atwhoblockobj['perfectScrollbar']({ horizrailenabled: false, zindex: 11111 });
        } catch (e) {
            writeLog("",e)
        }
    }

    loadReady(info){
        if(info == 'ready'){
            this.setState({rtInstanceReady:true})
            const { replyAdd} = this.props;
            const { setEditor } = replyAdd;
            this.loadJSAndInitAt();
            setEditor(this.rtInstance.editor,this.loadJSAndInitAt);
            const replyModal = $('.cube-reply-iframe').find(".ant-modal")
            if(replyModal.length>0 && replyModal.width()<768){
                replyModal.css("cssText","left:0px !important;")
            }
        }
    }

    loadJSAndInitAt = () => {
        const { visible,replyAdd,windowTop} = this.props;
        if (visible || replyAdd.popup) {
            const ckeditorid = this.rtInstance.editor.container.getId() || "";
            const iframeIndex = window !== window.top ? 0 : 1;
            const init = () => this.initAutoAt(windowTop.$(`#${ckeditorid}`).find('iframe')[iframeIndex]);
            loadjs.isDefined("atwhoJS")
            ? loadjs.ready("atwhoJS", init)
            : loadjs(
                [
                "/cloudstore/resource/pc/atwho/jquery.atwho_wev8.js",
                "/cloudstore/resource/pc/atwho/jquery.nicescroll_wev8.js",
                "/cloudstore/resource/pc/atwho/jquery.caret_wev8.js",
                "css!/cloudstore/resource/pc/atwho/jquery.atwho_wev8.css"
                ],
                "atwhoJS",
                init
            );
        }
    }


    saveAt = () =>{
        const ck:any = this.rtInstance;
        if(ck){
            ck.editor.undoManager.save()
        }
    }

    componentWillUnmount(){
        const { windowTop} = this.props;
        windowTop.CK_REF={}
    }
    getInstance = ins => {
        if (!this.rtInstance) {
           this.rtInstance = ins;
        }
      }


    render() {
        const { replyAdd,windowTop } = this.props;
        return (
            <div className="cube-reply-add">
                <WeaRichText
                    ref={this.getInstance} //'WeaRichText'
                    value={this.state.richContent}
                    //style={{ padding: "12px 10px 0 10px" }} QC:739626
                    ckConfig={{
                        toolbar: [
                            { nane: "document", items: ["Source"] },
                            { name: "paragraph", items: ["JustifyLeft", "JustifyCenter", "JustifyRight", "-", "NumberList", "BulletedList"] },
                            { name: "styles", items: ["Format", "Font", "FontSize"] },
                            { name: "color", items: ["TextColor"] },
                            { name: "basicstyles", items: ["Bold", "Italic", "Underline", "Strike"] },
                            { name: "insert", items: ["Table", "Smiley"] },
                        ],
                        extraPlugins: 'autogrow',
                        height: 185,
                        autoGrow_minHeight: 185,
                        autoGrow_maxHeight: 185,
                        removePlugins: 'resize',
                        uploadUrl: '/api/formmode/card/uploadimage',
                    }}
                    extentsConfig={this.getExtendsBar()}
                    bottomBarConfig={this.getbottomBar()}
                    onChange={replyAdd.onChange}
                    onToolsChange={this.toolsChange}
                    layout={windowTop}
                    onStatusChange={(info)=>{this.loadReady(info)}}
                />
            </div>
        )
    }
}

@observer
export class ReplyAddDialog extends React.Component<ReplyAddProps, any> {
    render() {
        const { replyAdd ,params,iconInfo} = this.props;
        const windowTop = WeaTools.WindowFunc.getTop();
        let windowNew:any //qc:#752287 iframe情况--window丢失
        let classNameDialog = "wea-auth-modal cube-dialog"
        if(windowTop.location.href.indexOf('cube/card')>-1){
            windowNew = windowTop;
        }else{
            windowNew = window;
            classNameDialog += ` cube-reply-iframe`;
        }
        const buttons = [<Button icon="cross" onClick={replyAdd.onCancel}>{getLabel(309, "关闭")}</Button>,
        <Button type="primary" icon="save" loading={replyAdd.loading} onClick={replyAdd.onOk}>{getLabel(615, '提交')}</Button>]
        return (
            <WeaDialog
                className={classNameDialog}
                buttons={buttons}
                title={getLabel(128283, '回复评论')}
                iconBgcolor={iconInfo.iconBg || "#96358a"}
                icon={iconInfo.icon || 'icon-coms-ModelingEngine'}
                iconFontColor={iconInfo.iconColor || "#fff"}
                visible={replyAdd.visible}
                style={{ width: '900px', height: '300px' }}
                hasScroll={true}
                onCancel={replyAdd.onCancel}
                layout={windowNew.document.body}
            >
               { replyAdd.visible && <ReplyAdd
                    replyAdd={replyAdd}
                    visible={replyAdd.visible}
                    params={params}
                    key="replyadd"
                    editorId="replyadd"
                    iconInfo={iconInfo}
                    windowTop={windowNew}
               />}
            </WeaDialog >
        )
    }
}

@observer
export class ReplyAddPopup extends React.Component<ReplyAddProps, any> {
    render() {
        const { replyAdd ,params,iconInfo} = this.props;
        const ClassNames = classnames('cube-replay-add-popup', {
            'cube-reply-add-popup-bottom': replyAdd.popupArrowPostion,
            'cube-reply-add-popup-top': !replyAdd.popupArrowPostion
        });
        const windowTop = window;
        return (
            <div
                ref="_container"
                className={ClassNames}
                style={{ display: `${replyAdd.popup ? 'block' : 'none'}`, ...replyAdd.popupOffset }} >
                {replyAdd.isInitPopup &&
                    <div style={{height:310,overflow:"scroll"}}>
                      {  <ReplyAdd replyAdd={replyAdd}
                            visible={replyAdd.visible} params={params}
                            key="replyaddpop" editorId="replyaddpop"
                            iconInfo={iconInfo}
                            windowTop={windowTop}
                      />}
                    </div>
                }
                <div className="cube-reply-add-popup-btn" >
                    <Button style={{ marginRight: 10 }} icon="cross" onClick={replyAdd.onPopupCancel}>{getLabel(309, "关闭")}</Button>
                    <Button type="primary" icon="save" loading={replyAdd.loading} onClick={replyAdd.onOk}>{getLabel(615, '提交')}</Button>
                </div>

            </ div>
        )
    }
}
